﻿using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Data;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Hosting.Internal;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace DX
{
    class DefaultNotifyCenter : INotifyCenter
    {
        public DefaultNotifyCenter(IRouterFactory routerFactory, IClassicDesktopStyleApplicationLifetime applicationLifetime)
        {


            this.applicationLifetime = applicationLifetime;
            this.option = routerFactory.Option;
        }
        readonly MvvmOption option;

        private readonly IClassicDesktopStyleApplicationLifetime applicationLifetime;
        TrayIcon notifyIcon;
        public void AddSeparator()
        {
            notifyIcon.Menu.Add(new NativeMenuItemSeparator());
        }
        public void Add(string title, Action handler)
        {
            if (!option.EnableNotifyIcon) return;
            notifyIcon.Menu.Add(new NativeMenuItem() { Header = title, Command = new RelayCommand(handler) });
        }

        public void Create()
        {
            if (!option.EnableNotifyIcon) return;
            notifyIcon = new TrayIcon();
            notifyIcon.Menu = new NativeMenu();
            notifyIcon.Icon = applicationLifetime.MainWindow.Icon;
            notifyIcon.ToolTipText = applicationLifetime.MainWindow.Title;
            notifyIcon.IsVisible = true;
            notifyIcon.Clicked += NotifyIcon_Clicked;
        }
        private DateTime? _trayTimeClick;
        private void NotifyIcon_Clicked(object sender, EventArgs e)
        {
            if (_trayTimeClick == null)
            {
                _trayTimeClick = DateTime.Now;
                return;
            }
            var delta = (DateTime.Now - _trayTimeClick).Value;
            if (delta.TotalMilliseconds > 500)
            {
                _trayTimeClick = DateTime.Now;
                return;
            }

            _trayTimeClick = null;
            var form = applicationLifetime.MainWindow;
            if (form.IsVisible)
            {
                form.Hide();
            }
            else
            {
                form.Show();
            }

        }

        public void Close()
        {
            notifyIcon.Clicked -= NotifyIcon_Clicked;
            notifyIcon.IsVisible = false;
            notifyIcon.Dispose();
        }
    }
}
